package com.icesoft.base.manager.config.register;

import cn.hutool.core.io.IoUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.icesoft.base.manager.entity.security.SysApiAuthority;
import com.icesoft.base.manager.entity.security.SysApiAuthorityGroup;
import com.icesoft.base.manager.service.security.SysApiAuthorityGroupService;
import com.icesoft.base.manager.service.security.SysApiAuthorityService;
import com.icesoft.core.common.util.JsonUtil;
import com.icesoft.core.web.helper.PathUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@AllArgsConstructor
@Slf4j
public class ApiAuthorityRegister implements ApplicationRunner {
    private SysApiAuthorityGroupService sysApiAuthorityGroupService;
    private SysApiAuthorityService sysApiAuthorityService;

    @Override
    public void run(ApplicationArguments args) {
        if (sysApiAuthorityGroupService.countAll() > 0) {
            return;
        }
        checkCreate();
    }

    private void checkCreate() {
        String json;
        try {
            json = IoUtil.readUtf8(PathUtil.getPathInputStream("config/apiAuthority.json"));
        } catch (IOException e) {
            log.error("权限文件读取失败", e);
            return;
        }
        List<SysApiAuthorityGroup> apiAuthorityGroups = JsonUtil.toObject(json, new TypeReference<List<SysApiAuthorityGroup>>() {
        });
        if (apiAuthorityGroups == null) {
            return;
        }
        for (SysApiAuthorityGroup group : apiAuthorityGroups) {
            SysApiAuthorityGroup apiAuthorityGroup = sysApiAuthorityGroupService.findByName(group.getName());
            if (apiAuthorityGroup == null) {
                apiAuthorityGroup = new SysApiAuthorityGroup();
                apiAuthorityGroup.setName(group.getName());
                apiAuthorityGroup.setPreUrl(group.getPreUrl());
                sysApiAuthorityGroupService.create(apiAuthorityGroup);
            }
            for (SysApiAuthority authority : group.getAuthorities()) {
                if (sysApiAuthorityService.findByGroupIdAndName(apiAuthorityGroup.getId(), authority.getName()) == null) {
                    authority.setGroupId(apiAuthorityGroup.getId());
                    sysApiAuthorityService.create(authority);
                }
            }
        }
    }
}
